package com.ooo.ttt.demo.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;

import com.ooo.ttt.demo.utils.DensityUtil;
import com.ooo.ttt.opencvlib.NativeFace;

import java.util.Timer;
import java.util.TimerTask;

public class CoverView extends View {
    private Paint paint;
    private NativeFace[] faces;

    private Thread mThread;
    private boolean mStartThread = true;
    private Timer timer;

    public CoverView(Context context) {
        this(context, null);
    }

    public CoverView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CoverView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        paint = new Paint();
        paint.setColor(Color.RED);
        paint.setStrokeWidth(2f);
        paint.setStyle(Paint.Style.STROKE);

        setBackgroundColor(Color.TRANSPARENT);
        timer = new Timer();


    }


    public void start() {
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                postInvalidate();
            }
        }, 100, 200);
    }

    public void stop() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }


    public NativeFace[] getFaces() {
        return faces;
    }

    public void setFaces(NativeFace[] faces) {
        this.faces = faces;
        invalidate();
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        if (faces != null && faces.length > 0) {
            for (int i = 0; i < faces.length; i++) {
                NativeFace face = faces[i];
                drawRect(face.x, face.y, face.width, face.height, canvas);
            }
        }
    }


    private void drawRect(int x, int y, int width, int height, Canvas canvas) {
//        int left = DensityUtil.dip2px(getContext(), x);
//        int top = DensityUtil.dip2px(getContext(), y);
//        int right = DensityUtil.dip2px(getContext(), x + width);
//        int bottom = DensityUtil.dip2px(getContext(), y + height);
        Log.e("tagRect", x + " " + y + " " + width + "  " + height);
        int left = x;
        int top = y;
        int right = x + width;
        int bottom = y + height;
        Log.e("tagRect2", left + " " + top + " " + right + "  " + bottom);
        if (canvas != null) {
            canvas.drawRect(left, top, right, bottom, paint);
        }
    }
}
